const http = require('http')
const url = require('url')
const path = require('path')
const fs = require('fs').promises
const querystring = require('querystring') // 引用querystring
const mime = require('mime')
const {createReadStream} = require('fs')
const ejs = require('ejs')
const {promisify} = require('util')

function mergeConfig(config) {
    return {
        port: 3000,
        directory: process.cwd(),
        ...config
    }
}

class Server {
    constructor(config) {
        this.config = mergeConfig(config)
    }

    start () {
        console.log('start')

        let server = http.createServer(async (req, res) => {
            console.log('请求')
            // console.log( new URL(req.url))
            // let [pathname] = new URL(req.url)
            let pathname = decodeURIComponent(req.url)
            try {
                let statObj = await fs.stat(path.join(this.config.directory, pathname))
                if  (statObj.isFile()) {
                    this.fileHandle(req, res, path.join(this.config.directory, pathname))
                } else {
                    let dirs = await fs.readdir(path.join(this.config.directory, pathname))
                    dirs = dirs.map(item => {
                        return {
                            path: path.join(pathname, item),
                            dirs: item
                        }
                    })
                    let randerFile = promisify(ejs.renderFile)
                    let ret = await ejs.renderFile(path.resolve(__dirname, 'template.html'), 
                    {
                        arr: dirs,
                        parent: path.join(this.config.directory, pathname) == '/' ? '': '上一层'
                    })
                    res.end(ret)
                }
            } catch (err){
                this.errorHandle(req, res, err)
            }

        })
        
        server.listen(this.config.port, () => {
            console.log('启动了')
        })
    }

    errorHandle (req, res, err) {
        res.statusCode = 404
        res.setHeader('Content-type', 'text/html;charset=utf-8')
        res.end('not found')
    }

    fileHandle (req, res, abs) {
        res.statusCode = 200
        res.setHeader('Content-type', mime.getType(abs)+';charset=utf-8')
        createReadStream(abs).pipe(res)
    }



}

module.exports  = Server